package middleware

import (
	"donkey-admin/internal/dao"
	"donkey-admin/internal/model/entity"
	"donkey-admin/utility"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gmeta"
	"github.com/google/uuid"
	"reflect"
)

// MiddlewareOperation 操作日志
func MiddlewareOperation(r *ghttp.Request) {
	token, err := utility.ParseToken(r.Context(), r.GetHeader("Authorization"))
	if err != nil {
		g.Log().Error(err)
	}

	r.Middleware.Next()

	//后置操作
	//g.Log().Info(r.Context(), r.Request.Response.Body)

	handler := r.GetServeHandler().Handler
	if handler.Info.Type != nil && handler.Info.Type.NumIn() == 2 {
		var objectReq = reflect.New(handler.Info.Type.In(1))

		_, err = dao.SysOperationLog.Ctx(r.GetCtx()).Insert(entity.SysOperationLog{
			Uuid:             uuid.New().String(),
			OperationPath:    r.URL.Path,
			OperationUser:    token.UserInfo.NickName,
			OperationIp:      r.GetClientIp(),
			OperationTime:    gtime.Now(),
			OperationAccount: token.UserInfo.UserName,
			OperationDesc:    gmeta.Get(objectReq, "summary").String(),
			ApiGroup:         gmeta.Get(objectReq, "tags").String(),
		})
		if err != nil {
			g.Log().Info(err)
		}
	}
}
